package com.woniu.order.controller;


import cn.hutool.core.bean.BeanUtil;
import com.alipay.api.AlipayApiException;
import com.woniu.model.Result;
import com.woniu.order.Form.ApplyForm;
import com.woniu.order.Param.ApplyParam;
import com.woniu.order.dto.RefundDto;
import com.woniu.order.model.Refund;
import com.woniu.order.service.RefundService;
import com.woniu.util.JwtUtil;
import com.woniu.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 杜岷芫
 * @since 2024年07月12日
 */
@RestController
@RequestMapping("/refund")
@Api(tags ="用户退款")
public class RefundController {
    @Resource
    private RefundService refundService;
    @Resource
    private RedisUtil redisUtil;


    // 用户申请退款

    @PostMapping("/apply")
    @ApiOperation("用户申请退款")
    public Result apply(@RequestBody ApplyForm form, @RequestHeader String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        int userId = Integer.parseInt(JwtUtil.parseUserToken(refreshToken).get("userId").toString());
        ApplyParam param = BeanUtil.toBean(form, ApplyParam.class);
        param.setUserId(userId);
        refundService.apply(param);
        return Result.getResult().setMsg("申请退款成功");
    }




     // 查询申请退款

    @GetMapping("/loadAllRefund")
    @ApiOperation("查询申请退款")
    public Result<List<RefundDto>> loadAllRefund(Integer refundState){
        List<RefundDto> list= refundService.loadAllRefund(refundState);
        return Result.getListResult(RefundDto.class).setData(list).setMsg("查询申请退款成功");
    }



    // 用户查询申请退款

    @GetMapping("/selctRefund")
    @ApiOperation("用户查询申请退款详情")
    public Result<List<Refund>> selctRefund(){
        List<Refund> list= refundService.selctRefund();
        return Result.getListResult(Refund.class).setData(list).setMsg("用户查询申请退款详情成功");
    }





   // 管理员同意退款 需要的参数 及后面的调用支付宝其他方法

    @GetMapping("/agreeRefund")
    @ApiOperation("管理员同意申请退款")
    public Result agreeRefund(String orderNum)throws AlipayApiException {
        refundService.sendRefundQueue(orderNum);
        return Result.getResult().setMsg("申请退款成功");
    }

    /**
     * 管理员驳回退款
     * @param refundId
     * @return
     * @throws AlipayApiException
     */
    @GetMapping("/rejectRefund")
    @ApiOperation("管理员驳回申请退款")
    public Result rejectRefund(Integer refundId)throws AlipayApiException {

        refundService.rejectRefund(refundId);
        return Result.getResult().setMsg("驳回退款申请成功");
    }



}

